package com.knife.message.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knife.message.app.service.KnifeUserMessageService;
import com.knife.message.domain.entity.KnifeMessage;
import com.knife.message.domain.entity.KnifeUserMessage;
import com.knife.message.infra.mapper.KnifeMessageMapper;
import com.knife.message.infra.mapper.KnifeUserMessageMapper;
import com.knife.oauth.domain.entity.IamUser;
import com.knife.oauth.infra.cache.v2.KnifeIamUserRedisCache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lth
 * @created 2025年09月11日 星期四 8:23
 */
@Service
public class KnifeUserMessageServiceImpl implements KnifeUserMessageService {
    @Resource
    private KnifeIamUserRedisCache knifeIamUserRedisCache;
    @Resource
    private KnifeUserMessageMapper knifeUserMessageMapper;
    @Resource
    private KnifeMessageMapper knifeMessageMapper;

    @Override
    public Page<KnifeMessage> selectPage(Page<KnifeMessage> pageRequest, KnifeMessage knifeMessage) {
        Page<KnifeMessage> knifeMessagePage = knifeMessageMapper.selectMessagePage(pageRequest, knifeMessage);
        for (KnifeMessage record : knifeMessagePage.getRecords()) {
            LambdaQueryWrapper<KnifeUserMessage> knifeUserMessageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            knifeUserMessageLambdaQueryWrapper
                    .eq(KnifeUserMessage::getMessageId, record.getMessageId());
            List<KnifeUserMessage> knifeUserMessageList = knifeUserMessageMapper.selectList(knifeUserMessageLambdaQueryWrapper);
            ArrayList<IamUser> iamUsers = new ArrayList<>();
            for (KnifeUserMessage userMessage : knifeUserMessageList) {
                IamUser param = new IamUser();
                param.setId(userMessage.getUserId());
                iamUsers.add(knifeIamUserRedisCache.getCache(param));
            }
            record.setReceiverList(iamUsers);
        }
        return knifeMessagePage;
    }

    @Override
    public Page<KnifeUserMessage> selectReceiverPage(Page<KnifeUserMessage> pageRequest, KnifeUserMessage knifeUserMessage) {
        LambdaQueryWrapper<KnifeUserMessage> knifeUserMessageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        knifeUserMessageLambdaQueryWrapper
                .eq(KnifeUserMessage::getMessageId, knifeUserMessage.getMessageId());
        Page<KnifeUserMessage> knifeUserMessagePage = knifeUserMessageMapper.selectPage(pageRequest, knifeUserMessageLambdaQueryWrapper);
        for (KnifeUserMessage record : knifeUserMessagePage.getRecords()) {
            IamUser param = new IamUser();
            param.setId(record.getUserId());
            record.setUser(knifeIamUserRedisCache.getCache(param));
        }
        return knifeUserMessagePage;
    }
}
